package com.bluezone.dec.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CacheConstant;
import com.bluezone.dec.common.PageEntity;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.system.dao.EntRelRectMapper;
import com.bluezone.dec.system.dao.RectPlanMapper;
import com.bluezone.dec.system.entity.EntRelRect;
import com.bluezone.dec.system.entity.RectPlan;
import com.bluezone.dec.system.service.EnterpriseService;
import com.bluezone.dec.system.service.RectPlanService;
import com.bluezone.dec.system.vo.EnterpriseVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author HHL
 * @description 专项整治计划服务层实现类
 * @date 2018/10/8 - 14:17
 */
@Service
public class RectPlanServiceImpl implements RectPlanService {

    @Autowired
    private RectPlanMapper rectPlanMapper;

    @Autowired
    private EntRelRectMapper entRelRectMapper;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AppConfig appConfig;

    /**
     * 从redis缓存中获取所有一企一档存在的企业列表[enterprise]信息
     *
     * @return
     */
    public List getEnterpriseListFromRedis() {

        if (Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.ENTERPRISE_CACHE_CONSTANT))) {
            return  this.getAllEnterprise();
        }

        String enterpriseMapList = redisTemplate.opsForValue().get(CacheConstant.ENTERPRISE_CACHE_CONSTANT);
        /* json 转 List<T> */
        return JSONArray.parseArray(enterpriseMapList, EnterpriseVo.class);
    }

    /**
     * 调取一企一档 获取企业列表接口获取企业列表信息并进行redis缓存
     *
     * @return
     */
    public List<EnterpriseVo> getAllEnterprise() {

        List<EnterpriseVo> enterpriseList = new ArrayList<>();

        JSONArray enterpriseListArray =  enterpriseService.getAllEnterprise();

        /* 遍历json数组， 获取所需字段 */
        for (int i = 0; i < enterpriseListArray.size(); i++) {
            EnterpriseVo enterpriseMap = new EnterpriseVo();
            JSONObject jsonObject = enterpriseListArray.getJSONObject(i);
            enterpriseMap.setEntName(jsonObject.get(SystemConstant.NAME).toString());
            enterpriseMap.setEntCode(jsonObject.get("credit_code").toString());
            enterpriseList.add(enterpriseMap);
        }

        /* List<T> 转 json */
        String enterpriseJsonList = JSON.toJSONString(enterpriseList);

        redisTemplate.opsForValue().set(CacheConstant.ENTERPRISE_CACHE_CONSTANT,
                enterpriseJsonList,
                appConfig.getEnterpriseDataCacheTime(),
                TimeUnit.SECONDS);

        return enterpriseList;
    }

    /**
     * 从redis缓存中获取所有专项整治计划[plan]信息
     *
     * @return
     */
    @Override
    public List<RectPlan> getPlanListFromRedis() {

        if (Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.PLAN_CACHE_CONSTANT))) {
            return this.findAllPlanDetail();
        }

        String allPlanList = redisTemplate.opsForValue().get(CacheConstant.PLAN_CACHE_CONSTANT);
        return  JSONArray.parseArray(allPlanList, RectPlan.class);
    }


    /**
     * 查询所有计划的详细信息
     *
     * @return
     */
    @Override
    public List<RectPlan> findAllPlanDetail() {

        List<RectPlan> rectPlanList = rectPlanMapper.findAllPlanDetail();

        /* 添加专项整治计划信息列表redis缓存并设置缓存过期时间 */
        redisTemplate.opsForValue().set(CacheConstant.PLAN_CACHE_CONSTANT,
                JSON.toJSONString(rectPlanList),
                appConfig.getChartDataCacheTime(),
                TimeUnit.SECONDS);

        return rectPlanList;
    }

    /**
     * 计算专项整治计划表里所有的企业数
     *
     * @return
     */
    @Override
    public int getTotalPlanCounts() {
        return rectPlanMapper.getTotalPlanCounts();
    }

    /**
     * 根据计划id查询专项整治计划
     *
     * @param id
     * @return
     */
    @Override
    public RectPlan get(String id) {
        return rectPlanMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据计划id删除专项整治计划
     *
     * @param planId
     * @return
     */
    public int deletePlanById(String planId) {

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.PLAN_CACHE_CONSTANT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.PLAN_CACHE_CONSTANT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.TASK_CENSUS))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.TASK_CENSUS);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.INVEST_STATISTIC))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.INVEST_STATISTIC);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.UNFINISH_RECTIFICATION_COUNT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.UNFINISH_RECTIFICATION_COUNT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.SCHEDULE_TASKS_IMPLEMENT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.SCHEDULE_TASKS_IMPLEMENT);
        }

        return rectPlanMapper.deleteByPrimaryKey(planId);
    }

    /**
     * 根据传递的map参数，动态分页查询专项整治记录数据
     *
     * @param params
     * @return
     */
    @Override
    public PageEntity<RectPlan> findByParams(Map<String, Object> params) {

        int pageNum = (int) params.get("pageNum");// 页码
        int pageSize = (int) params.get("pageSize"); // 页大小

        List<RectPlan> list = null;
        PageInfo<RectPlan> pageInfo = null;

        if (pageNum != 0 && pageSize != 0) {
            PageHelper.startPage(pageNum, pageSize); // PageHelper分页插件分类
            list = rectPlanMapper.findByParams(params);
            pageInfo = new PageInfo(list);
        }

        return PageEntity.toPageEntity(pageInfo);
    }

    /**
     * 查询该计划名称是否已存在
     *
     * @param rectName 专项整治计划名称
     * @return
     */
    @Override
    public int findPlanName(String rectName) {
        return rectPlanMapper.findPlanName(rectName);
    }

    /**
     * 查询所有的专项整治id及其对应的名称
     *
     * @return
     */
    @Override
    public List<RectPlan> findAllRectPlan() {
        return rectPlanMapper.findAllRectPlan();
    }

    /**
     * 添加专项整治计划
     *
     * @param rectPlan
     * @return
     */
    @Override
    public int save(RectPlan rectPlan) {

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.PLAN_CACHE_CONSTANT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.PLAN_CACHE_CONSTANT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.TASK_CENSUS))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.TASK_CENSUS);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.INVEST_STATISTIC))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.INVEST_STATISTIC);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.UNFINISH_RECTIFICATION_COUNT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.UNFINISH_RECTIFICATION_COUNT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.SCHEDULE_TASKS_IMPLEMENT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.SCHEDULE_TASKS_IMPLEMENT);
        }

        return rectPlanMapper.insertSelective(rectPlan);
    }

    /**
     * 添加专项整治计划及其关联企业
     *
     * @param entRelRect
     * @return
     */
    public int addEntRelRect(EntRelRect entRelRect) {
        return entRelRectMapper.insertSelective(entRelRect);
    }

    /**
     * 根据专项整治计划id修改专项整治计划
     *
     * @param rectPlan
     * @return
     */
    @Override
    public int update(RectPlan rectPlan) {

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.PLAN_CACHE_CONSTANT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.PLAN_CACHE_CONSTANT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.TASK_CENSUS))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.TASK_CENSUS);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.INVEST_STATISTIC))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.INVEST_STATISTIC);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.UNFINISH_RECTIFICATION_COUNT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.UNFINISH_RECTIFICATION_COUNT);
        }

        if (!Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.SCHEDULE_TASKS_IMPLEMENT))) {
            redisTemplate.opsForValue().getOperations().delete(CacheConstant.SCHEDULE_TASKS_IMPLEMENT);
        }

        return rectPlanMapper.updateByPrimaryKeySelective(rectPlan);
    }

    @Override
    public int remove(String id) {
        return 0;
    }

    @Override
    public int batchRemove(String... ids) {
        return 0;
    }

    @Override
    public List<RectPlan> findAll() {
        return new ArrayList<>();
    }
}
